# -*- coding: utf-8 -*-
from odoo import http
import json
import sys
import os
import jinja2
import datetime
from odoo.http import request

if hasattr(sys, 'frozen'):
    # When running on compiled windows binary, we don't have access to package loader.
    path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'views'))
    loader = jinja2.FileSystemLoader(path)
else:
    loader = jinja2.PackageLoader('odoo.addons.customer', "static/bi")

jinja_env = jinja2.Environment(loader=loader, autoescape=True)
jinja_env.filters["json"] = json.dumps

index_html = jinja_env.get_template('index.html')


class DateEncoder(json.JSONEncoder):
    def default(self, obj):
        """date_time转化方法"""
        if isinstance(obj, datetime.datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, datetime.date):
            return obj.strftime("%Y-%m-%d")
        elif isinstance(obj, bytes):
            return str(obj, encoding='utf-8')
        else:
            return json.JSONEncoder.default(self, obj)


class BiInfo(http.Controller):

    @http.route(['/bi/main'], type='http', auth="none")
    def get_main_page(self):
        # 组装返回数据
        orders_data = request.env['customer.model'].sudo().search_read([],
                                                                       ['name', 'width', 'height', 'color'])
        length = len(orders_data)
        data = {'orders_data': orders_data,
                'length': length}
        return index_html.render(data)

    @http.route(['/bi/data'], type='http', auth="none", methods=['post'], csrf=False)
    def get_main_data(self):
        # 组装返回数据
        data = {'axis': ['1', '2', '3', '4', '5'],
                'axis2': ['2', '6', '1', '3', '5']}
        return json.dumps(data)

